package com.blog.serlvet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.blog.bean.BaseResponse;
import com.blog.bean.User;
import com.blog.dao.UserDao;
import com.blog.util.MD5Util;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

public class RegisterServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String phone = req.getParameter("phone");
        String password = req.getParameter("password");

        resp.setContentType("text/json;charset=UTF-8");
        PrintWriter writer = resp.getWriter();

        // 校验参数
        if (phone == null || phone.length() != 11) {
            writer.println(JSONObject.toJSONString(new BaseResponse(400, "手机号不正确", null)));
            return;
        }
        if (password == null || password.length() < 6 || password.length() > 20) {
            writer.println(JSONObject.toJSONString(new BaseResponse(400, "密码不正确", null)));
            return;
        }

        UserDao userDao = new UserDao();
        // 检查手机号是否重复
        User user = null;
        try {
            user = userDao.selectByPhone(phone);
        } catch (SQLException e) {
            e.printStackTrace();
            resp.sendError(500);
            return;
        }
        if (user != null) {
            writer.println(JSONObject.toJSONString(new BaseResponse(400, "手机号已经被别人注册", null)));
            return;
        }

        try {
            userDao.insertUser(phone, MD5Util.md5(password));
        } catch (SQLException e) {
            e.printStackTrace();
            resp.sendError(500);
            return;
        }
        writer.println(JSONObject.toJSONString(new BaseResponse(200, "注册成功", null)));
    }
}
